package admin

import (
	"last/app/models"
	"last/pkg/database"
)

type Posts struct {
	models.BaseModel
	IsTop         int        `json:"is_top"`
	IsHot         int        `json:"is_hot"`
	ViewsCount    int        `json:"views_count"`
	CommentsCount int        `json:"comments_count"`
	CategoryId    int        `json:"category_id"`
	Categories    Categories `json:"category" gorm:"ForeignKey:CategoryId"`
	Banner        string     `json:"banner"`
	Summary       string     `json:"summary"`
	Content       string     `json:"content"`
	Title         string     `json:"title"`
	Text          string     `json:"text"`
	models.CommonTimestampsField
}

// Store 新增
func (p *Posts) Store(data interface{}) bool {
	result := database.DB.Model(Posts{}).Create(data)
	return result.RowsAffected == 1
}

// List 列表
func (p *Posts) List(page, pageSize int, where map[string]interface{}) (error, int64, interface{}) {
	query := database.DB.Model(Posts{}).Preload("Categories")
	var total int64
	var results []Posts
	if where["title"] != "" {
		query.Where("title=?", where["title"])
	}
	if where["text"] != "" {
		query.Where("text=?", where["text"])
	}
	query.Count(&total)
	return query.Offset((page - 1) * pageSize).
		Limit(pageSize).
		Find(&results).Error, total, results
}

// Edit 更新
func (p *Posts) Edit(id int, data map[string]interface{}) error {
	return database.DB.Model(Posts{}).Where("id=?", id).Updates(&data).Error
}

// Show 详情
func (p *Posts) Show(id string, data interface{}) error {
	return database.DB.Model(Posts{}).Where("id=?", id).Preload("Categories").Find(data).Error
}

// Remove 删除
func (p *Posts) Remove(id string, data interface{}) error {
	return database.DB.Model(Posts{}).Where("id=?", id).Delete(&data).Error
}
